/*
 * @Author: hulu20 - 563293401@qq.com
 * @Date: 2023-02-11 14:53:47
 * @Last Modified by: hulu20 - 563293401@qq.com
 * @Last Modified time: 2023-02-13 10:20:34
 * @Desc: 实现与数据库交互业务的封装
 */

package logic

import (
	"context"
	"fmt"
	"tasktor/internal/dao"
	"tasktor/internal/model/entity"
	"tasktor/library/liberr"

	"github.com/gogf/gf/v2/frame/g"
)

var TaskMonitorLogic = taskMonitorLogic{} // 对外提供方法，变量大写

type taskMonitorLogic struct{}

// 变量名大写，否则暴露不了func
func (s *taskMonitorLogic) GetMonitorData(ctx context.Context, time int64) (res []*entity.TaskMonitorLog, err error) {
	//res = new(model.TaskMonitorInfo)
	err = g.Try(ctx, func(ctx context.Context) {
		//model := dao.TaskMonitorLog.Ctx(ctx) // 注意生成dao模型的时候，非default库添加分组，否则会执行default库调用
		model := g.Model(dao.TaskMonitorLog.Table(), "a").Ctx(ctx) // 由于要使用别名连表，使用g.db模式
		// 连表获取数据
		model = model.RightJoin(fmt.Sprintf("SELECT max(id) as id2 from %s WHERE start_at >= %d GROUP BY task_name", dao.TaskMonitorLog.Table(), time), "b", "a.id = b.id2")

		// 获取数据
		err = model.Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
	})
	return
}
